<template>
  <div class="main-wrapper">
    <!-- 专业类别筛选 -->
    <!--<div class="content-filterbox">
			<div class="content-filter">
				<div class="content-filtername">专业：</div>
				<div v-for="(item, index) in majorTree" :key="`major${index}`" class="content-filteritem" :class="`${ item.id === currentMajor.id ? 'active' : ''}`" @click="handleMajorChange(item)">{{ item.text }}</div>
			</div>
			<div class="content-filter">
				<div class="content-filtername">分类：</div>
				<div class="content-filteritem" v-show="!loadingData">请选择专业</div>
				<div v-for="(item, index) in currentMajor.children" :key="`type${index}`" class="content-filteritem" :class="`${ item.id === currentType.id ? 'active' : ''}`" @click="currentType = item; simulationResourcePage()">{{ item.text }}</div>
			</div>
		</div>-->
    <!-- 用户咨询 -->
    <div class="fictitious_rightBtnsbox">
      <div class="zxd" v-if="this.$store.state.im.messages.code == 2"></div>
      <div class="zxbox" @click.stop="listshow = !listshow">
        <div class="zx tool">
          <img src="@/images/zixunac.png" alt="" srcset="" class="normal" />
          <img src="@/images/zixunac.png" alt="" srcset="" class="active" />
        </div>
        <div class="zxdes">咨询</div>
      </div>
    </div>
    <!-- 联系人列表 -->
    <div class="listbox beautifulScroll" v-show="listshow">
      <div class="listtile">联系人列表</div>

      <div class="listboxmain beautifulScroll">
        <div
          v-for="item in userlist"
          :key="item.userId"
          class="listitem"
          @click="classroomIdfn(item.userId)"
        >
          <div class="listitemimg">
            <img
              :src="item.iconurl"
              alt=""
              v-img-error="handleImageError"
              v-if="item.avatar"
            />
            <img src="@/images/user_infoicon.png" v-else />
          </div>
          <div
            class="userzxd"
            v-if="messagesfromId.includes(item.userId)"
          ></div>
          <div class="listname">{{ item.name }}</div>
          <div class="listnames">查看</div>
          <div class="xxxtx" v-if="messagesfromId.includes(item.userId)">
            <img src="@/images/xxxtx.png" alt="" />
          </div>
          <!--  -->
        </div>
      </div>
    </div>
    <!-- 用户聊天 -->
    <vimVue
      :classroomId="classroomId"
      v-show="vimshow"
      @closeTalk="closeTalk"
      @classroomIdfns="classroomIdfns"
      class="vim"
    />
    <!-- 搜索栏 -->
    <div class="search-wrapper">
      <el-form :inline="true" :model="params" class="demo-form-inline">
        <el-form-item label="实验名称">
          <el-input v-model="params.name" placeholder="实验名称" clearable />
        </el-form-item>
        <el-form-item label="实验标识">
          <el-input v-model="params.code" placeholder="实验标识" clearable />
        </el-form-item>
        <el-form-item label="组织机构">
          <el-select
            v-model="params.orgId"
            placeholder="请选择组织机构"
            clearable
          >
            <el-option
              v-for="item in depts"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="createLimit"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="simulationResourcePage()"
          ></el-date-picker>
        </el-form-item>
        <el-button type="primary" @click="simulationResourcePage()"
          >查询</el-button
        >
        <el-button @click="createResource()" type="primary">添加实验</el-button>
      </el-form>
    </div>

    <div class="page-wrapper" v-if="resources.length > 0">
      <div class="sy" v-for="item in resources" :key="item.index">
        <div class="syfmimg">
          <!-- <img :src="item.cover" alt="" /> -->
          <el-image :src="item.cover" class="cover-content" fit="cover">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline">图片资源失效</i>
            </div>
          </el-image>
        </div>
        <div class="syname">{{ item.name }}</div>
        <div class="syzzjg">
          <div>组织机构</div>
          <div v-show="item.deptName != null">{{ item.deptName }}</div>
          <div v-show="item.deptName == null">暂无分配</div>
        </div>
        <div class="syupdate">
          <div>最近更新时间</div>
          <div>{{ item.createTime }}</div>
        </div>
        <div class="syments">
          <div class="bjments" @click="showResourceInfo(item.id)">
            <i class="el-icon-edit-outline"></i>
            编辑
          </div>
          <div class="bjments" @click="showResourceDelete(item.id)">
            <i class="el-icon-delete"></i>
            删除
          </div>
          <div class="bjments" @click="showResourceUpdate(item.id)">
            <i class="el-icon-edit"></i>
            更新
          </div>
          <div class="bjments bjmentss" @click="showRecordingFn(true, item.id)">
            <i class="el-icon-tickets"></i>
            记录
          </div>
          <div class="bjments bjmentss">
            <el-tooltip
              :content="item.state == 0 ? '开启' : '关闭'"
              placement="top"
            >
              <el-switch
                :active-value="item.state == 0"
                :inactive-value="item.state == 1"
                @change="showResourceStatus(item)"
              >
              </el-switch
            ></el-tooltip>
          </div>
        </div>
      </div>
      <div style="width: 100%;margin: 15px;text-align: center;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.current"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
        ></el-pagination>
      </div>
    </div>
    <div class="page-wrapper zygxjl zygxjls" v-else>暂无实验资源</div>
    <!-- 仿真实验列表 -->

    <!-- 记录弹窗 -->

    <el-dialog
      :visible.sync="showRecording"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      @close="beforecolse"
      class="jldialog"
    >
      <div class="jlbox">
        <div
          class="jlan"
          :class="updatestep == 1 ? 'jlandt' : ''"
          @click="updatestepFn(1)"
        >
          更新记录
        </div>
        <div
          class="jlan"
          :class="updatestep == 2 ? 'jlandt' : ''"
          @click="updatestepFn(2)"
        >
          反馈记录
        </div>
        <div
          class="jlan"
          :class="updatestep == 3 ? 'jlandt' : ''"
          @click="updatestepFn(3)"
        >
          访问记录
        </div>
      </div>
      <div class="jlnrbox">
        <div v-if="updatestep == 1">
          <resource-update
            ref="resourceRecords"
            :resourceId="resourceUpdateId"
            v-if="resourceUpdateId"
          />
        </div>
        <div v-if="updatestep == 2">
          <resource-back :resourceId="resourceBackId" v-if="resourceBackId" />
        </div>
        <div v-if="updatestep == 3">
          <resource-open
            :resourceId="resourceOpenId"
            v-if="resourceUpdateId"
            ref="resourcebacks"
          />
        </div>
      </div>
    </el-dialog>

    <!-- 新增 编辑 更新 -->
    <el-dialog
      :title="resource.name ? resource.name : '新增虚拟仿真实验'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :class="updateshow ? 'changeStyles' : 'changeStyle'"
    >
      <!-- <resource-edit
        ref="edit"
        :resource="resource"
        :isModify="isModify"
        class="dialog-content"
        v-if="!updateshow"
      /> -->
      <div class="form-wrappers" v-if="!updateshow">
        <el-form
          :model="resource"
          :rules="rules"
          ref="form"
          class="form-wrapper"
        >
          <el-row class="syfm">
            <el-form-item prop="url" label="实验资源">
              <div
                class="drop-area el-upload-dragger"
                @click="clickElement($event, 'upload_folder')"
                @drop="handleFileDrop($event)"
                @dragleave="stopEvent($event)"
                @dragenter="stopEvent($event)"
                @dragover="stopEvent($event)"
              >
                <!-- <i class="el-icon-upload"></i> -->

                <img src="@/images/syzyicon.png" alt="" class="teximg" />

                <div class="el-upload__text">
                  请将资源文件目录拖拽到此处,或点此添加
                  <br />
                  <!-- TODO 在方法中判断 -->
                  <div class="scjd">
                    <em v-if="allFileNum > 0 && allFileNum === upFileNum"
                      >已上传</em
                    >
                    <em v-if="allFileNum > 0 && allFileNum > upFileNum"
                      >正在上传：{{ upFileNum }}/{{ allFileNum }}</em
                    >
                  </div>
                  <!-- <em v-if="!isModify && allFileNum == 0" style="color: #F56C6C;"
                >未上传, 请选择目录</em
              > -->
                  <div
                    class="zyscts"
                    v-if="!allFileNum && isModify"
                    v-html="resourceMessage"
                  ></div>
                  <input
                    ref="upload_folder"
                    webkitdirectory
                    type="file"
                    accept="*"
                    style="display: none"
                    @change="handleFileInput($event)"
                  />
                </div>
              </div>
            </el-form-item>
            <el-form-item prop="cover" label="实验封面" class="drop-areas">
              <el-upload
                action="#"
                accept=".jpg, .png, .jpeg"
                :http-request="option => handleFileUpload(option, 'cover')"
                :before-upload="checkImageType"
                :show-file-list="false"
                class="drop-area el-upload-dragger"
              >
                <el-image
                  v-if="resource.cover"
                  :src="resource.cover"
                  class="upload-content"
                  fit="contain"
                ></el-image>
                <div v-else>
                  <div v-if="coverFlag">
                    <el-progress
                      type="circle"
                      :percentage="coverProgress"
                      style="margin: 25px 0 0 0 ;"
                    ></el-progress>
                  </div>
                  <div v-else>
                    <img src="@/images/syfmicon.png" alt="" class="teximg " />
                    <div class="el-upload__text">请上传封面</div>
                  </div>
                </div>
              </el-upload>
            </el-form-item>
          </el-row>
          <el-row class="symc">
            <el-form-item prop="name" label="实验名称">
              <el-input v-model="resource.name" class="sykdx" />
            </el-form-item>
            <el-form-item prop="code" label="实验标识" class="drop-areas">
              <el-input v-model="resource.code" class="sykdx" />
            </el-form-item>
          </el-row>
          <el-row class="symc">
            <el-form-item prop="deptId" label="组织机构">
              <el-select
                v-model="resource.deptId"
                placeholder="请选择组织机构"
                class="sykdx"
                @change="getDepUser"
              >
                <el-option
                  v-for="item in depts"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 回显接口得修改 userlistID 或者提交接口修改 -->
            <el-form-item prop="userList" label="联系人" class="drop-areass">
              <el-select
                v-model="resource.userList"
                collapse-tags
                placeholder="请选择联系人"
                class="sykdx"
                multiple
              >
                <el-option
                  v-for="item in deptUsers"
                  :key="item.userId"
                  :label="item.name"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row class="symc">
            <el-form-item prop="mode" label="实验模式">
              <el-select
                v-model="resource.mode"
                collapse-tags
                placeholder="请选择实验模式"
                class="sykdx"
              >
                <el-option
                  v-for="item in modedata"
                  :key="item.Id"
                  :label="item.name"
                  :value="item.Id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item
              prop="introductionJson.content"
              label="实验简介"
              class="syjj"
            >
              <vue-editor
                id="editor"
                v-model="resource.introductionJson.content"
                :editorToolbar="editorToolbar"
              />
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <updates
        ref="update"
        class="dialog-content"
        v-if="updateshow"
        :resource="resource"
        :isModify="isModify"
      />
      <div
        slot="footer"
        :class="updateshow ? 'dialog-footers' : 'dialog-footer'"
      >
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submit()" :disabled="dataloading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 新增
import { VueEditor } from 'vue2-editor'
import { createMultipartUpload, listObjects } from '@/utils/oss.js'
import {
  listResourceMode,
  listMajorByPid,
  checkCode
} from '@/api/simulation.js'
import { majorList } from '@/api/major.js'

// 新增结束
import RequestUtils from '@/utils/RequestUtils'
import { mapState } from 'vuex'

// import WebsocketHeartbeatJs from '@/utils/websocketIm'
import ResourceEdit from './edit'
import ResourceBack from './back'
import ResourceUpdate from './update'
import ResourceOpen from './open'
import { getInfo } from '@/api/sysUser'
import { getToken } from '@/utils/auth'
import { deptList, deptUser } from '@/api/sysDept.js'
import {
  simulationState,
  simulationResourcePage,
  getSimulationResource,
  saveSimulationResource,
  updateSimulationResource,
  removeSimulationResource,
  majorTree,
  updateResources
} from '@/api/simulation.js'
import Updates from './updates.vue'
import { userlist } from '@/api/user.js'
import vimVue from '@/components/vim.vue'
export default {
  name: 'simulationResource',
  components: {
    ResourceBack,
    ResourceUpdate,
    ResourceOpen,
    Updates,
    vimVue,
    VueEditor
  },
  data() {
    //
    // const that = this
    // const validateCode = (rule, value, callback) => {
    //   checkCode(value, that.resource.id || '').then(({ data }) => {
    //     callback(data ? undefined : new Error('实验标识已存在'))
    //   })
    // }
    return {
      showRecording: false,
      updateshow: false,
      depts: [],
      params: {}, // 实验查询参数
      createLimit: [], // 实验查询参数时间区间
      resources: [], // 实验资源列表
      pageInfo: {
        limit: 10
      }, // 实验资源列表分页参数
      dialogVisible: false, // 控制编辑模态框状态\
      resource: {
        introductionJson: {
          content: ''
        },
        userList: []
        // major_id: 1,
        // type_id: 1
      }, // 当前操作的实验
      isModify: true, // 当前操作实验是否为编辑模式(初始化后不可改变的值在编辑模式下应禁用修改)
      majorTree: [], // 专业参数树
      currentMajor: {}, // 当前所选专业详情
      currentType: {}, // 当前所选类别详情
      dataloading: false,
      loadingData: false,
      dialogBack: false,
      resourceBackId: '',
      dialogUpdate: false,
      resourceUpdateId: '',
      dialogOpen: false,
      resourceOpenId: '',
      userinfo: {},
      updatestep: 1,
      updatejlid: '',
      userlist: [],
      listshow: false,
      classroomId: '',
      vimshow: false,
      messageList: [],
      messagesfromId: [], //一下是新增
      validateCode: '',
      modedata: [
        {
          Id: 'old',
          name: '旧版'
        },
        {
          Id: 'new',
          name: '新版'
        },
        {
          Id: 'exam',
          name: '考核'
        }
      ],
      userList: [],
      mode: '',
      modes: [], // 实验模式参数列表
      majors: [], // 专业参数列表
      types: [], // 类别参数列表
      isLock: false, // `isLock: true` 后可以上传文件, 禁止上传后修改路径
      objects: [],
      videoFlag: false,
      videoProgress: 0,
      coverFlag: false,
      coverProgress: 0,
      allFileNum: 0,
      upFileNum: 0,
      resourceMessage: '', // 资源上传框提示信息

      deptUsers: [], //学生信息
      vrTypes: [
        {
          id: '国家申报',
          title: '国家申报'
        },
        {
          id: '定制化',
          title: '定制化'
        }
      ],

      // 表单校验
      rules: {
        name: [
          {
            required: true,
            message: '请输入实验名称',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入实验标识',
            trigger: 'blur'
          },
          {
            required: true,
            validator: this.validateCode,
            trigger: 'blur'
          }
        ],
        version: [
          {
            required: true,
            message: '请输入版本号',
            trigger: 'blur'
          }
        ],
        introductionJson: {
          content: [
            {
              required: true,
              message: '请输入实验简介',
              trigger: 'blur'
            }
          ]
        },
        cover: [
          {
            required: true,
            message: '请上传实验封面',
            trigger: 'blue'
          }
        ],
        url: [
          {
            required: true,
            message: '请上传实验资源',
            trigger: 'blue'
          }
        ],
        mode: [
          {
            required: true,
            message: '请选择实验模式',
            trigger: 'change'
          }
        ],
        // majorId: [
        //   {
        //     required: true,
        //     message: '请选择专业',
        //     trigger: 'change'
        //   }
        // ],
        deptId: [
          {
            required: true,
            message: '请选择所属组织机构',
            trigger: 'change'
          }
        ],
        userList: [
          {
            required: true,
            message: '请选择联系人',
            trigger: 'change'
          }
        ],
        vrType: [
          {
            required: true,
            message: '请选择实验类别',
            trigger: 'change'
          }
        ],
        typeId: [
          {
            required: true,
            message: '请选择类别',
            trigger: 'change'
          }
        ]
      },
      // 富文本参数
      editorToolbar: [
        [
          {
            header: [false, 1, 2, 3, 4, 5, 6]
          },
          'bold',
          'italic',
          'underline',
          {
            align: ''
          },
          {
            align: 'center'
          },
          {
            align: 'right'
          }
        ],
        [
          {
            list: 'ordered'
          },
          {
            list: 'bullet'
          },
          {
            list: 'check'
          }
        ],
        [
          {
            background: []
          },
          {
            color: []
          }
        ],
        ['strike'],
        ['clean']
      ]
    }
  },
  created() {
    // RequestUtils.getInstance().webSocketOperation(this)
    this.simulationResourcePage()
    this.getMajorTree()
    this.getDeptList()
    this.getInfo()
    this.userListfn()

    this.$store.watch(
      () => this.$store.state.im.messages,
      (newUser, oldUser) => {
        if (newUser.code == 2) {
          console.log('消息来源id', newUser.message.fromId)
          this.messagesfromId.push(newUser.message.fromId)
          const targetIndex = this.userlist.findIndex(
            item => item.userId == newUser.message.fromId
          )

          if (targetIndex !== -1) {
            // 移除原来的位置
            const removedUser = this.userlist.splice(targetIndex, 1)
            // 将该用户信息插入数组开头
            this.userlist.unshift(removedUser[0])
            console.log('更新后的消息列表', this.userlist)
          }
        }
      }
    )
    // 新增
    this.getDepUser()
    this.initForm()
    // 新增结束
  },
  computed: {
    // ...mapState(['messages'])
  },
  methods: {
    // 新增
    getDepUser() {
      if (!this.resource.deptId) {
        return
      }
      this.resource.userList = []
      deptUser(this.resource.deptId).then(async res => {
        this.deptUsers = res.data
        console.log('查询了当前组织下的联系人', this.deptUsers)
        // this.resource.userList[0] = JSON.parse(
        //   JSON.stringify(this.resource.userIdList[0])
        // )

        if (this.deptUsers.length < 1) {
          this.resource.userList = []
        }
        if (this.resource.userIdList) {
          this.resource.userIdList.forEach(item => {
            this.resource.userList.push(item)
          })

          console.log('当前已绑定用户', this.resource.userList)
          // this.$set(this.resource, 'userList', this.resource.userIdList)
          // this.$forceUpdate()
        } else {
          this.resource.userList = []
        }
      })
    },
    // ==================== 文件上传 ====================
    /**
     * 图片 / 视频上传
     */
    handleFileUpload(option, attribute) {
      const { file } = option
      const suffix = file.name.slice(file.name.lastIndexOf('.'))
      const { majorId, typeId, code, version } = this.resource
      const key = `vrOrg/${majorId}/${typeId}/${code}/${version}/${attribute}/${this.createUUID()}${suffix}`
      createMultipartUpload(key, file, (progress, checkpoint) => {
        if (!checkpoint) {
          return
        }
        this[`${attribute}Flag`] = true
        this[`${attribute}Progress`] = Math.round(progress * 100)
      }).then(res => {
        const url = res.res.requestUrls[0]
        this.$set(
          this.resource,
          attribute,
          url.indexOf('?') === -1 ? url : url.slice(0, url.indexOf('?'))
        )
        this.videoFlag = false
        this.videoProgress = 0
        this.coverFlag = false
        this.coverProgress = 0
      })
    },
    checkSuccess() {
      this.allFileNum = this.objects.length
      this.upFileNum = this.objects.filter(
        item => item.uploading === false
      ).length
      if (this.allFileNum == this.upFileNum) {
        this.$refs['upload_folder'].value = ''
      }
    },
    /**
     * 资源文件上传
     * @param {File} file 本地文件
     * @param {String} relativePath 文件相对路径
     */
    handleResourceUpload(file, relativePath) {
      this.resource.attachPrefix = ''
      // 获取上传文件的文件名标识
      var a = relativePath.indexOf('/')
      var l = relativePath.substring(0, a)
      // this.resource.name = l
      // this.resource.code = l
      this.$set(this.resource, 'name', l)
      this.$set(this.resource, 'code', l)
      // 正式上传代码
      const that = this
      const { majorId, typeId, code, version } = this.resource
      const key = `vrOrg/${majorId}/${typeId}/${code}/${version}/${relativePath}`
      // 检查重复上传
      let index = this.objects.findIndex(item => item.key === key)
      if (index > -1) {
        this.objects[index].file = file
        return
      }
      // 上传
      this.objects.push({
        key: key,
        file: file,
        uploading: true
      })
      createMultipartUpload(key, file, this.multiUploadProgress).then(
        ({ name, res }) => {
          const target = that.objects.find(object => object.key === key)
          target.uploading = false
          // 更新lock状态
          that.checkSuccess()
          if (that.upFileNum === that.allFileNum) {
            that.$set(that, 'isLock', false)
          }
          // 通过任一 url 截取资源文件父目录, 通过 json 文件地址截取资源名称
          // url: http://zf-vr.oss-cn-hangzhou.aliyuncs.com/6/8/jyjb1/1.0.0/Build/MRWebGl.json
          const durl = /https?:\/\/[\w.:\-_%]*\/[\w.\-_%]*\/[\w.\-_%]*\/[\w.\-_%]*\/[\w.\-_%]*\/[\w.\-_%]*\/[\w.\-_%]*\//i
          const jurl = /[\w.:\-_\/%]*\/Build\/[\w.\-_%]*.json/i //旧版本
          const jurls = /[\w.:\-_\/%]*\/Build\/[\w.\-_%]*.data/i //新版本
          this.resource.url = res.requestUrls[0].match(durl)[0]

          console.log('上传完成返回1', res, this.mode)

          if (this.resource.mode == 'new') {
            console.log('上传完成返回newd', res, this.mode)
            if (name && name.match(jurls)) {
              const node = res.requestUrls[0].split('/')
              this.resource.attachPrefix = node[node.length - 1]
                .replace('.data', '')
                .split('?')[0]

              console.log('上传完成返回new32', this.resource.attachPrefix)
            }
          } else {
            if (name && name.match(jurl)) {
              const node = res.requestUrls[0].split('/')
              console.log('上传完成返回', this.resource.attachPrefix)
              this.resource.attachPrefix = node[node.length - 1].replace(
                '.json',
                ''
              )

              // console.log('上传完成返回', this.resource.attachPrefix)
            }
          }

          console.log('上传获取json', this.resource, this.resource.attachPrefix)

          // if (file.name == 'fm.png') {
          //   that.handleFileUpload(file, 'cover')
          //   // this.resource.cover =
          //   console.log('file.name', file.name)
          // }
        }
      )
    },
    /**
     * 分片上传进度
     * @param {Number} progress 分片上传进度, 取值范围: 0~1
     * @param {Object} checkpoint 本地分片上传结果
     */
    multiUploadProgress(progress, checkpoint) {
      if (!checkpoint) {
        return
      }
      const target = this.objects.find(item => item.key === checkpoint.name)
      this.$set(target, 'checkpoint', checkpoint)
      this.$set(target, 'progress', Math.round(progress * 100))
    },
    /**
     * 点击上传文件 / 目录
     */
    handleFileInput(event) {
      const that = this

      this.checkField()
        .then(() => {
          // 校验通过, 上传, 禁止修改
          this.isLock = true
          for (const file of event.target.files) {
            that.handleResourceUpload(
              file,
              file.webkitRelativePath || file.name
            )
            // console.log('判断文件类型是不是图片如果是判定为封面file', file.name)
          }
        })
        .catch(() => {
          // 不通过, 清空上传
          this.$refs['upload_folder'].value = ''
        })
    },
    /**
     * 拖拽上传文件 / 目录
     */
    handleFileDrop(event) {
      this.stopEvent(event)
      this.checkField()
        .then(() => {
          this.isLock = true
          const items = event.dataTransfer.items
          if (!items.length || items[0].kind !== 'file') return
          for (const item of items) {
            const entry = item.webkitGetAsEntry()
            this.loadChildFiles(entry, entry.name)
          }
        })
        .catch(() => {
          this.$refs['upload_folder'].value = ''
        })
      // console.log('执行文件上传', this.resource.name)
    },
    /**
     * 递归获取文件
     * @param {FileSystemEntry|FileSystemDirectoryEntry} entry 文件 / 目录
     * @param {String} relativePath 文件/目录相对路径
     */
    loadChildFiles(entry, relativePath) {
      // if (!this.resource.name && !this.resource.code) {
      //   var a = relativePath.indexOf('/')
      //   var l = relativePath.substring(0, a)
      //   this.resource.name = l
      //   this.resource.code = l
      // }

      const that = this
      if (entry.isFile) {
        entry.file(file => that.handleResourceUpload(file, relativePath))
        return
      }
      const reader = entry.createReader()
      reader.readEntries(entries =>
        entries.forEach(entry =>
          that.loadChildFiles(
            entry,
            `${relativePath ? relativePath : ''}/${entry.name}`
          )
        )
      )
    },
    // ==================== 页面动作 ====================
    /**
     * 初始化页面
     */
    initForm() {
      this.objects = []
      // this.$set(this.resource, 'majorId', '1')
      // this.$set(this.resource, 'typeId', '1')
      // 初始化 userList 为空数组（防止初始 undefined）
      // this.$set(this.resource, 'userList', [])
      // this.checkOSSResource()
    },
    async checkOSSResource() {
      // 验证 OSS 文件目录存在
      const { res } = await listObjects(this.resource.url)
      this.resourceMessage =
        res.requestUrls && res.requestUrls.length
          ? `<em style="color: #67C23A">服务器存在本实验资源</em>`
          : '<em style="color: #F56C6C">资源已被删除, 需重新上传</em>'
      console.log(this.resourceMessage)
    },
    /**
     * 数据处理, 表单验证
     */
    beforeSubmit() {
      if (this.allFileNum > this.upFileNum) {
        this.$message('文件上传中')
        return false
      }
      const { content } = this.resource.introductionJson
      const text = content.replace(/<[^>]+>/g, '')
      this.resource.introduction = JSON.stringify({
        content,
        text
      })
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          if (!valid) {
            return false
          }
          resolve()
        })
      })
    },
    /**
     * 上传参数全部通过
     */
    checkField() {
      const that = this
      const filed = ['version', 'mode']
      //  const filed = ['code', 'version', 'mode']
      return new Promise((resolve, reject) => {
        let success = true
        that.$refs['form'].validateField(filed, error => {
          if (error) {
            success = false
          }
        })
        if (success) {
          resolve()
        } else {
          this.$refs['upload_folder'].value = ''
          this.$message.error('请检查上传必要参数')
        }
      })
    },
    resetForm() {
      this.$refs['form'].resetFields()
      this.deptUsers = null
    },
    // ==================== 参数列表 ====================
    /**
     * 选择专业重置类型
     */
    resetType() {
      this.$set(this.resource, 'typeId', null)
      this.listType()
    },
    /**
     * 实验资源使用模式
     */
    listResourceMode() {
      listResourceMode().then(({ code, msg, data }) => {
        this.modes = data
      })
    },
    /**
     * 专业查询
     */
    listMajor() {
      majorList({}).then(res => {
        this.majors = res.children
      })
    },
    /**
     * 类型查询
     */
    listType() {
      listMajorByPid(this.resource.majorId).then(({ code, msg, data }) => {
        this.types = data
      })
    },
    // ==================== utils ====================
    /**
     * 图片格式验证
     */
    checkImageType({ type }) {
      const isPic = type.startsWith('image')
      if (!isPic) {
        this.$message.error('封面必须是 图片！')
      }
      return isPic
    },
    /**
     * 视频格式验证
     */
    checkVideoType({ type }) {
      const isVideo = type.startsWith('video')
      if (!isVideo) {
        this.$message.error('演示必须是 视频！')
      }
      return isVideo
    },
    /**
     * 阻止浏览器默认操作
     */
    stopEvent(event) {
      event.stopPropagation()
      event.preventDefault()
    },
    /**
     * 模拟点击
     */
    clickElement(event, el) {
      event.stopPropagation()
      this.$refs[el].click()
    },
    /**
     * 随机串
     */
    createUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        let r = (Math.random() * 16) | 0,
          v = c == 'x' ? r : (r & 0x3) | 0x8
        return v.toString(16)
      })
    },
    // 新增结束
    closeTalk() {
      this.vimshow = false
    },
    classroomIdfns(id) {
      const index = this.messagesfromId.indexOf(id)
      if (index !== -1) {
        // 如果 userId 存在于 messagesfromId 数组中，移除它
        this.messagesfromId.splice(index, 1)
      }
    },
    classroomIdfn(id) {
      this.classroomId = id
      this.vimshow = true
      this.classroomIdfns(id)
    },
    userListfn() {
      userlist().then(async res => {
        this.userlist = res.data
        // console.log('获取消息列表', this.userlist)
      })
    },
    beforecolse() {
      this.updatestep = 1
      this.resourceBackId = null
      console.log('执行了关闭前回调')
      if (this.$refs.resourceRecords) {
        this.$refs.resourceRecords.resourceRecords = []
      }
      if (this.$refs.resourcebacks) {
        this.$refs.resourcebacks.resourcebacks = []
      }
    },
    handleImageError(event) {
      // console.error('图片加载失败:', event)

      // 替换为默认图片
      event.target.src = require('@/images/user_infoicon.png') // 替换为你的默认图片路径
    },
    updatestepFn(i) {
      if (i == 1) {
        this.updatestep = 1
        this.showResourceUpdatejl(this.updatejlid)
      } else if (i == 2) {
        this.updatestep = 2
        this.showResourceBack(this.updatejlid)
      } else if (i == 3) {
        this.updatestep = 3
        this.showResourceOpen(this.updatejlid)
      }
    },
    showRecordingFn(i, id) {
      this.showRecording = i
      this.updatestep = 1
      this.updatejlid = id
      this.showResourceUpdatejl(this.updatejlid)
    },
    getDeptList() {
      deptList({}).then(async res => {
        this.depts = res.children
      })
    },
    getInfo() {
      var token = getToken()
      getInfo().then(res => {
        this.userinfo = res.data
      })
    },
    /**
     * 分页查询
     */
    simulationResourcePage() {
      if (this.currentType.id == null) {
        this.loadingData = true
      }
      this.params.majorId = this.currentMajor.id
      this.params.typeId = this.currentType.id
      this.params.createStart = this.createLimit ? this.createLimit[0] : null
      this.params.createEnd = this.createLimit ? this.createLimit[1] : null
      this.params.systemType = 'admin'
      simulationResourcePage(Object.assign(this.params, this.pageInfo)).then(
        ({ code, msg, data }) => {
          if (code !== 'OK') {
            this.$message('系统出错, 请联系管理员')
            return
          }
          const { records, current, size, total } = data
          this.resources = records
          this.pageInfo = {
            current,
            total,
            limit: size
          }
          this.loading = false
        }
      )
    },
    /**
     * 删除
     */
    showResourceDelete(resourceId) {
      this.$confirm('是否删除该虚拟仿真实验?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          removeSimulationResource(resourceId).then(({ code, msg, data }) => {
            if (code !== 'OK') {
              this.$message.error(msg)
              return
            }
            this.$message.success('已删除!')
            this.simulationResourcePage()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    /**
     * 新增
     */
    saveResource() {
      // this.resource.deptId = this.resource.orgId
      // this.records.userList = this.resource.contactsInfo

      saveSimulationResource(this.resource).then(({ code, msg, data }) => {
        if (code === 'OK') {
          this.$message.success('已添加')
          this.dialogVisible = false
          this.simulationResourcePage()
        } else if (code === 'INVALID_PARAMETERS') {
          this.$message.error(data)
        } else {
          this.$message.error(msg)
        }
      })
    },
    /**
     * 修改
     */
    async updateResource(i) {
      // console.log('更新内容', this.resource)
      // this.resource.deptId = this.resource.orgId
      // this.records.userList = this.resource.contactsInfo
      // this.resource.userList = this.userList
      if (i) {
        console.log('更新内容', this.resource)
        this.resourcedata = {
          id: this.resource.id,
          attachPrefix: this.resource.attachPrefix,
          url: this.resource.url,
          context: this.resource.context
        }
        updateResources(this.resourcedata).then(({ code, data }) => {
          if (code === 'OK') {
            this.$message.success('已修改')
            this.dialogVisible = false
            this.simulationResourcePage()
          }
        })
      } else {
        updateSimulationResource(this.resource).then(({ code, data }) => {
          if (code === 'OK') {
            this.$message.success('已修改')
            this.dialogVisible = false
            this.simulationResourcePage()
          }
        })
      }
    },
    /**
     * 专业查询参数获取
     */
    getMajorTree() {
      majorTree().then(({ children }) => {
        this.majorTree = children
      })
    },
    handleMajorChange(major) {
      if (this.currentMajor === major) {
        return
      }
      this.currentMajor = major
      this.currentType = {}
      this.simulationResourcePage()
    },
    createResource() {
      this.resource = {
        version: '1.0.0',
        sort: 1,
        state: 0,
        introductionJson: {
          content: ''
        }
      }
      this.isModify = false
      this.openDialog()

      if (this.$refs['edit']) {
        this.$refs['edit'].resetForm()
      }
    },
    showResourceStatus(item) {
      var textInfo = '确认启用实验？'
      var state = '1'
      if (item.state == '1') {
        textInfo = '确认禁用实验?'
        state = '0'
      }
      this.$confirm(textInfo, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          simulationState({
            resourceId: item.id,
            state: state
          }).then(({ code, msg, data }) => {
            if (code !== 'OK') {
              this.$message.error(msg)
              return
            }
            this.$message.success('已修改!')
            this.simulationResourcePage()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    async showResourceInfo(resourceId) {
      const { code, msg, data } = await getSimulationResource(resourceId)
      data.version = data.version || '1.0.0'
      data.introductionJson = JSON.parse(data.introduction)
      this.resource = data
      this.isModify = true

      if (code == 'ok') {
        console.log('执行了查询', code)
        this.resource.userList = this.resource.userId
        console.log('执行了查询', this.resource.userList)
      }

      this.openDialog()

      // if (code == 'ok') {
      //   console.log('执行了查询', code)

      //   // if (this.$refs.edit) {
      //   //   this.$refs.edit.getDepUser()
      //   // }
      // }
      //
      // this.resource.userList = [this.resource.userIdList[0]]
      //
    },
    async showResourceUpdate(resourceId) {
      const { code, msg, data } = await getSimulationResource(resourceId)
      data.version = data.version || '1.0.0'
      data.introductionJson = JSON.parse(data.introduction)
      this.resource = data
      this.isModify = true
      this.openDialogs()
    },
    showResourceUpdatejl(resourceId) {
      this.resourceUpdateId = resourceId
      // this.dialogUpdate = true
    },
    showResourceBack(resourceId) {
      this.resourceBackId = resourceId
      this.dialogBack = true
    },
    showResourceOpen(resourceId) {
      this.resourceOpenId = resourceId
      // this.dialogOpen = true
    },
    openDialogs() {
      if (this.$refs.update) {
        this.$refs.update.initForm()
      }
      this.dialogVisible = true
      this.updateshow = true
    },
    openDialog() {
      this.initForm()
      this.getDepUser()

      // if (this.$refs.edit) {
      //   this.$refs.edit.initForm()
      //   this.$refs.edit.getDepUser()
      // }
      this.dialogVisible = true
      this.updateshow = false
    },
    submit() {
      if (this.updateshow) {
        this.updateResource(true)
        // console.log('更新')
      }
      this.dataloading = true
      setTimeout(_ => {
        this.dataloading = false
      }, 1000)
      if (!this.$refs.edit) {
        return
      }
      this.$refs.edit
        .beforeSubmit()
        .then(() => {
          this.isModify
            ? this.updateResource(this.updateshow)
            : this.saveResource()
        })
        .catch(err => {
          console.log(err)
        })
      this.$refs.edit.userList = []
    },
    cancel() {
      // 编辑页第一次初始化 || 未锁定
      if (!this.$refs.edit || !this.$refs.edit.isLock) {
        this.dialogVisible = false
        return
      }
      if (this.$refs.edit) {
        this.$refs.edit.deptUser = []
        this.$refs.edit.userList = []
      }
      // 文件上传中提示
      this.$confirm('资源上传中，是否取消上传？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 重设表单
          this.$refs.edit.resetForm()
          // 更改状态框打开状态
          this.dialogVisible = false
          this.$message.success('已取消')
        })
        .catch(() => {})
    },
    handleCurrentChange(page) {
      this.pageInfo.current = page
      this.simulationResourcePage()
    },
    handleSizeChange(size) {
      this.pageInfo.limit = size
      this.pageInfo.currnet = 1
      this.simulationResourcePage()
    }
  }
}
</script>
<style>
.zygxjls {
  text-align: center;
  display: flex;
  align-content: center;
  justify-content: center;
}
</style>

<style scoped>
.el-form-item {
  display: flex !important;
}
.drop-area {
  width: 359px;
  height: 143px;
  /* line-height: 143px; */
}
.drop-areas {
  margin-left: 50px;
}
.drop-areass {
  margin-left: 64px;
}
.syfm {
  display: flex;
}
.el-form-item--medium .el-form-item__content {
  line-height: 0px !important;
}
.teximg {
  margin-top: 25px;
}
.symc {
  display: flex;
}
.zyscts {
  margin-top: -13px;
}
.scjd {
  margin-top: -13px;
}
</style>
